/*
 * Copyright (C) 2011 by Anton Novikau
 * 
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 * 
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */

package com.googlecode.gplaces.core;

import android.location.Criteria;
import android.location.Location;
import android.location.LocationManager;
import android.os.Handler;
import android.os.HandlerThread;

/**
 * Class that is used to obtain current location using the most suitable
 * LocationProvider. Manager resolves current location coordinates
 * asyncronously, so {@link #onObtainStart()} and
 * {@link #onObtainFinish(Location)} callbacks could be implemented to show the
 * progress.
 * 
 * @author Anton Novikov
 */
public class LocationObtainer {
    private static final String TAG = LocationObtainer.class.getSimpleName();

    private final LocationManager locationManager;

    private final Handler uiHandler = new Handler();

    private HandlerThread backgoundThread;

    /**
     * Creates an instance of LocationObtainer.
     * 
     * @param locationManager used for accessing system location services
     */
    public LocationObtainer(LocationManager locationManager) {
        this.locationManager = locationManager;
    }

    /**
     * Starts current location obtaining.
     */
    public final void start() {
        backgoundThread = new HandlerThread(TAG) {
            @Override
            protected void onLooperPrepared() {
                // select the best suitable location provider and subscribe for
                // location updates.
                Criteria providerCriteria = new Criteria();
                providerCriteria.setPowerRequirement(Criteria.POWER_MEDIUM);
                final String provider = locationManager.getBestProvider(providerCriteria, true);
                locationManager.requestLocationUpdates(provider, 0, 0, new LocationListener());
            }
        };
        backgoundThread.start();

        onObtainStart();
    }

    /**
     * Callback being called when obtaining location started. Useful to show
     * execution progress.
     */
    protected void onObtainStart() {}

    /**
     * Callback being called when obtaining location finished.
     * 
     * @param location current location provided by location service
     */
    protected void onObtainFinish(Location location) {}

    /**
     * Location listener implementation that monitors for changing location and
     * posts result to UI thread.
     * 
     * @author Anton Novikov
     */
    private class LocationListener extends LocationListenerAdapter {

        @Override
        public void onLocationChanged(final Location location) {
            locationManager.removeUpdates(LocationListener.this);
            // post to UI that location is obtained.
            uiHandler.post(new Runnable() {
                @Override
                public void run() {
                    onObtainFinish(location);
                }
            });
            backgoundThread.quit();
        }
    }
}
